<template>
  <view class="">
    <c-navBar title="新增教练"></c-navBar>
    <view>
      <CForm
        :formRules="formRules"
        v-model:formData="formData"
        :formList="formList"
        @submit="submit"
        :type="type"
      ></CForm>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue"
import CForm from "@/components/CForm/CForm.vue"
import {
  addTeacher,
  getTeacherDetail,
  saveTeacher
} from "@/apis/coachManagement.js"
import { onLoad, onUnload, onBackPress } from "@dcloudio/uni-app"

import { addCoachForm } from "./data"
const { formField, formList, formRules } = addCoachForm
const defaultData = JSON.parse(JSON.stringify(formField))
let formData = ref(JSON.parse(JSON.stringify(formField)))
let teacher_id = ref("")
let type = ref("")
onBackPress(() => {
  formData.value = JSON.parse(JSON.stringify(defaultData))
})
onLoad((options) => {
  teacher_id.value = options.teacher_id
  type.value = options.type
  // formList[2].options =
  if (teacher_id.value) {
    getDetail()
  }
})
const getDetail = () => {
  getTeacherDetail({ teacher_id: teacher_id.value }).then((res) => {
    if (res.code === 1) {
      formData.value = res.data || {}
    }
  })
}
const submit = () => {
  if (teacher_id.value) {
    edit()
  } else {
    add()
  }
}
const add = () => {
  console.log(formData.value)
  addTeacher(formData.value).then((res) => {
    if (res.code === 1) {
      uni.showSuccessToast("添加成功！")
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    }
  })
}

const edit = () => {
  saveTeacher({
    ...formData.value,
    teacher_id: teacher_id.value
  }).then((res) => {
    if (res.code === 1) {
      uni.showSuccessToast("修改成功！")
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        })
      }, 1500)
    }
  })
}
</script>

<style></style>
